package com.filldream.fastboot.common.util;


import com.filldream.fastboot.common.exception.GlobalException;
import com.filldream.fastboot.common.entity.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import weixin.popular.api.MessageAPI;
import weixin.popular.bean.message.templatemessage.TemplateMessage;
import weixin.popular.bean.message.templatemessage.TemplateMessageResult;

/**
 * 微信推送模板工具
 * @author RickSun
 * 2020-05-22 10:34:00
 */
@Slf4j
public class WxTemplateUtil {

    //模板默认颜色
    private static final String COLOR = "#173177";

    /**
     * @author RickSun
     * @Description 发送模板
     * @param accessToken 公众号的accessToken
     * @param templateMessage 消息模板
     * 注：openId和accessToken都为公众号的，且公众号为服务号；url和小程序优先跳转小程序，小程序无法跳转则跳转url
     * 参考:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html#5
     * 参考:https://blog.csdn.net/qq_35350654/article/details/106221420
     **/
    public void send(String accessToken,TemplateMessage templateMessage){
        log.info("---->开始发送短信模板:{}",templateMessage);
        Assert.isEmpty( accessToken,"accessToken为空");
        if( StringUtils.isEmpty(templateMessage.getUrl()) ){
            templateMessage.setUrl("https://4m.cn/8pHoi");
        }
        TemplateMessageResult templateMessageResult = MessageAPI.messageTemplateSend(accessToken, templateMessage);
        String errcode = templateMessageResult.getErrcode();
        String errmsg = templateMessageResult.getErrmsg();
        if (!StringUtils.isEmpty(errcode) && !"0".equals(errcode)) {
            log.error("SendTemplate log ErrCode:{} ErrMsg:{}", errcode, errmsg);
            throw new GlobalException(ErrorCode.MSG_TEMPLATE_ERR.reMsg(),errmsg);
        }
        long msgid = templateMessageResult.getMsgid();
        log.debug("SendTemplate msgid= " + msgid);
    }


}
